package Huihu.src.Duoxiancheng;
/*
产生死锁的四大要素
1、互斥条件：一个资源只能被一个进程占有
2、请求与保持条件：一个进程因请求资源而阻塞时，对以获得的资源保持不放
3、不剥夺条件：进程已获得的资源，再没有使用完之前，不能进行强行剥夺
4、循环等待条件：诺干进程之间形成一种头尾相接的循环等待资源
要想接除死锁，只要破开产生死锁的要素中的任何一条
 */
public class DeadLock {
    public static void main(String[] args) {
        Makeup makeup1=new Makeup(0,"灰姑凉");
        Makeup makeup2=new Makeup(2,"白雪公主");
        new Thread(makeup1).start();
        new Thread(makeup2).start();
    }
}

class Lipstick{

}

class Mirror{

}

class Makeup extends Thread{
    static Lipstick lipstick=new Lipstick();
    static Mirror mirror=new Mirror();//静态对象被所有对象共享
    int choice;//选择
    String girlName;//用镜子的女孩

    public Makeup(int choice, String girlName) {
        this.choice = choice;
        this.girlName = girlName;
    }

    @Override
    public void run() {
        //化妆
        try {
            makeup();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public void makeup() throws InterruptedException {
        if (choice==0) {
            synchronized(lipstick){
                System.out.println(this.girlName+"获得口红的锁");
                Thread.sleep(1000);
                synchronized(mirror){
                    System.out.println(this.girlName+"获得镜子的锁");
                }
            }
        }else {
            synchronized(mirror) {
                System.out.println(this.girlName + "获得镜子的锁");
                Thread.sleep(1000);
                synchronized (lipstick) {
                    System.out.println(this.girlName + "获得口红的锁");
                }
            }
        }
    }
    /*
    //解锁
    public void makeup() throws InterruptedException {
        if (choice==0) {
            synchronized(lipstick){
                System.out.println(this.girlName+"获得口红的锁");
                Thread.sleep(1000);
            }
            synchronized(mirror){
                    System.out.println(this.girlName+"获得镜子的锁");
                }
        }else {
            synchronized(mirror) {
                System.out.println(this.girlName + "获得镜子的锁");
                Thread.sleep(1000);
            }
            synchronized (lipstick) {
                    System.out.println(this.girlName + "获得口红的锁");
                }
        }
    }
     */
}
